<template>
  <edit-dialog-component
    v-bind="$attrs"
    :width="width"
    :scoped-slots="$scopedSlots"
    :loading="loading"
    @submit="submit"
    @open="open"
    @opened="opened"
    @close="close"
  >
    <slot name="header" />
    <form-component
      ref="form"
      v-loading="loading"
      v-bind="$attrs"
      :configs="config"
      :params="params"
      :data="data"
    >
      <slot />
    </form-component>
    <template v-if="$scopedSlots['extra-button']" slot="extra-button">
      <slot name="extra-button" />
    </template>
  </edit-dialog-component>
</template>

<script>
import EditDialogComponent from 'modules/component/EditDialog'
import FormComponent from 'modules/component/template/Form'
import EditDataMixin from 'modules/mixins/edit-data'
import { filterNotInConfigs } from 'modules/utils/params'

export default {
  components: {
    EditDialogComponent,
    FormComponent
  },
  mixins: [EditDataMixin],
  inheritAttrs: false,
  props: {
    configs: {
      type: [Array, Object],
      default() {
        return []
      }
    },
    isResetParams: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '55%'
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    config() {
      return Object.hasOwnProperty.call(this.configs, 'fields')
        ? this.configs.getFields({
          data: this.params,
          params: {
            ...this.$attrs
          }
        })
        : this.configs
    }
  },
  methods: {
    submit(callback) {
      const params = this.$refs.form.submit()
      filterNotInConfigs(this.config, params)
      this.$emit('submit', { params, callback })
    },
    close() {
      this.$emit('close')
    },
    open() {
      this.$nextTick(() => {
        this.$emit('open')
      })
    },
    opened() {
      this.$nextTick(() => {
        this.$emit('opened')
      })
      if (this.isResetParams) {
        this.resetParams()
        this.$refs.form.resetParams && this.$refs.form.resetParams()
      }
    }
  }
}
</script>
